import {
  Injectable,
  NestInterceptor,
  ExecutionContext,
  CallHandler,
} from '@nestjs/common';
import { Observable, map } from 'rxjs';

export interface ResponseFormat<T = any> {
  code: number;
  msg: string;
  data: T;
}

@Injectable()
export class ResponseIntercepotor<T>
  implements NestInterceptor<T, ResponseFormat<T>>
{
  intercept(
    context: ExecutionContext,
    next: CallHandler,
  ): Observable<ResponseFormat<T>> {
    return next.handle().pipe(
      map((data) => ({
        code: 0, // 成功默认 0
        msg: '操作成功!',
        // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
        data: data === undefined ? null : data,
      })),
    );
  }
}
